package com.atomscat.lottery.config.exception;

import com.atomscat.lottery.entity.vo.response.BaseResponse;
import com.atomscat.lottery.service.VoBaseRespTransformService;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@ResponseBody
@RestControllerAdvice(basePackages = {"com.atomscat.lottery"})
@RequiredArgsConstructor
@ResponseStatus(code = HttpStatus.OK)
public class OsControllerAdvice {

    private final VoBaseRespTransformService voBaseRespTransformService;

    @ExceptionHandler(WebExchangeBindException.class)
    public BaseResponse handleValidationErrors(WebExchangeBindException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getFieldErrors().forEach(error -> {
            errors.put(error.getField(), error.getDefaultMessage());
        });
        return voBaseRespTransformService.transformBadRequest(errors);
    }

    @ExceptionHandler(ExpiredJwtException.class)
    public BaseResponse exceptionHandler(ExpiredJwtException e) {
        log.error("ExpiredJwtException: ", e);
        return voBaseRespTransformService.transformExpiration(e.getMessage());
    }

    @ExceptionHandler(JwtException.class)
    public BaseResponse exceptionHandler(JwtException e) {
        log.error("ExpiredJwtException: ", e);
        return voBaseRespTransformService.transformInvalid(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public BaseResponse exceptionHandler(Exception e) {
        log.error("ExpiredJwtException: ", e);
        return voBaseRespTransformService.transformUnavailable(e.getMessage());
    }
}
